<template>
	<div class="front bg-white bj">
		<el-scrollbar style="height: 100%;">
			<div class="form">
				<el-form :model="formData" ref="formRef" :disabled="!isEdit" :rules="formRules" label-position="left" label-width="150px" class="demo-ruleForm">
					<el-form-item label="公司名称：" prop="companyNameChinese">
						<el-input v-model.trim="formData.companyNameChinese" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="公司名称（英文）：" prop="companyNameEnglish">
						<el-input v-model.trim="formData.companyNameEnglish" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="账套名：" prop="accountSet">
	                    <el-input v-model.trim="formData.accountSet"></el-input>
	                </el-form-item>
	                <el-form-item label="注册码：" prop="registrationCode">
	                    <el-input v-model.trim="formData.registrationCode"></el-input>
	                </el-form-item>
	                <el-form-item label="公司简称（中文）：" prop="companyAbbreviationChinese">
	                    <el-input v-model.trim="formData.companyAbbreviationChinese"></el-input>
	                </el-form-item>
	                <el-form-item label="公司简称（英文）：" prop="companyAbbreviationEnglish">
	                    <el-input v-model.trim="formData.companyAbbreviationEnglish"></el-input>
	                </el-form-item>
	                <el-form-item label="行业大类：" prop="industry">
	                    <el-select v-model="formData.industry" filterable placeholder="选择行业" style="width: 100%">
	                        <el-option v-for="item in industry" :key="item['id']" :label="item['icName']" :value="item['id']"></el-option>
	                    </el-select>
	                </el-form-item>
	                <el-form-item label="税号：" prop="dutyParagraph">
	                    <el-input v-model.trim="formData.dutyParagraph"></el-input>
	                </el-form-item>
	                <el-form-item label="银行账号：" prop="bankAccount">
	                    <el-input v-model.trim="formData.bankAccount"></el-input>
	                </el-form-item>
	                <el-form-item label="国家：" prop="countryId">
	                    <el-select v-model="formData.countryId" filterable placeholder="选择国家" style="width: 100% !important">
	                        <el-option v-for="item in countries" :key="item['id']" :label="item['name']" :value="item['id']"></el-option>
	                    </el-select>
	                </el-form-item>
	                <el-form-item label="省份：" prop="proviceId">
	                    <el-select v-model="formData.proviceId" filterable :loading="loading" loading-text="数据加载中..." placeholder="选择省份" style="width: 100% !important">
	                        <el-option v-for="item in provinces" :key="item['id']" :label="item['name']" :value="item['id']"></el-option>
	                    </el-select>
	                </el-form-item>
	                <el-form-item label="城市：" prop="cityId">
	                    <el-select v-model="formData.cityId" filterable :loading="loading" loading-text="数据加载中..." placeholder="选择城市" style="width: 100% !important">
	                        <el-option v-for="item in cities" :key="item['id']" :label="item['name']" :value="item['id']"></el-option>
	                    </el-select>
	                </el-form-item>
	                <el-form-item label="区/县：" prop="areaId">
	                    <el-select v-model="formData.areaId" filterable :loading="loading" loading-text="数据加载中..." placeholder="选择区/县" style="width: 100% !important">
	                        <el-option v-for="item in areas" :key="item['id']" :label="item['name']" :value="item['id']"></el-option>
	                    </el-select>
	                </el-form-item>
	                <el-form-item label="详细地址（中文）：">
	                    <el-input v-model.trim="formData.addressChinese" placeholder="输入详细地址"></el-input>
	                </el-form-item>
	                <el-form-item label="地址（英文）：" prop="addressEnglish">
	                    <el-input v-model.trim="formData.addressEnglish"></el-input>
	                </el-form-item>
	                <el-form-item label="电话：" prop="phone">
	                    <el-input v-model.trim="formData.phone"></el-input>
	                </el-form-item>
	                <el-form-item label="传真：" prop="fax">
	                    <el-input v-model.trim="formData.fax"></el-input>
	                </el-form-item>
	                <el-form-item label="邮箱：" prop="email">
	                    <el-input v-model.trim="formData.email"></el-input>
	                </el-form-item>
	                <!-- 版本号 -->
	                <el-form-item label="版本号：" prop="version">
	                    <el-select v-model="currentVesion" style="width: 100% !important">
	                        <el-option v-for="(item, index) in version" :key="index" :label="item" :value="index"></el-option>
	                    </el-select>
	                </el-form-item>
	                <div class="line">
		                <el-form-item label="代码：" prop="currencyCode">
		                    <el-input v-model="formData.currencyCode" disabled></el-input>
		                </el-form-item>
		                <el-form-item label="名称：" prop="currencyName">
		                    <el-select v-model="formData.currencyName" filterable style="width: 100%; !important" @change="selectCurrentName">
		                        <el-option v-for="item in allUnit" :key="item['id']" :label="item['name']" :value="item['name']"></el-option>
		                    </el-select>
		                </el-form-item>
		                <el-form-item label="小位数：" prop="smallDigit">
		                    <el-input v-model.trim="formData.smallDigit" disabled></el-input>
		                </el-form-item>
		            </div>
				</el-form>
			</div>
		</el-scrollbar>
	</div>
</template>
<script>
/*
*  author: 'iissoftware'
*  description: 系统信息组件
*/
export default {
	data() {
		var checkEmail = (rule, value, callback) => {           //校验邮箱格式是否正确
            if(value) {
                let reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
                if(!reg.test(value)) {
                    callback(new Error('邮箱格式不正确'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        }
		return {
			systemId: this.$store.state.systemId,
			status: this.$store.state.accountStore.status,
			formData: {
				currencyCode: 'RMB',
                currencyName: '人民币',
                smallDigit: 2
			},
			formRules: {
				companyNameChinese: [{required: true, message: '公司名称不能为空', triggle: 'blur'}],
                industry: [{required: true, message: '行业大类不能为空'}],
                industryInfo: [{required: true, message: '细分行业不能为空'}],
                accountSet: [{required: true, message: '账套名不能为空', triggle: 'blur'}],
                registrationCode: [{required: true, message: '注册码不能为空', triggle: 'blur'}],
                email: [{validator: checkEmail, trigger: 'blur'}]
			},
			industry: this.$store.state.accountStore.industry,		//行业大类
			countries: [],		//国家
			provinces: [],		//省份
			cities: [],			//城市
			areas: [],			//区县
			currentVesion: 0,	//当前版本
			version: ['v1.0'],
			isEdit: true,		//是否可编辑信息
			isEditRegCode: true,
			loading: true,
			allUnit: []
		}
	},
	watch: {
		'formData.countryId'(newVal, oldVal) {		//监听国家变化，清空子级数据
			if(oldVal && (newVal != oldVal)) {
				this.formData['proviceId'] = '';
				this.formData['cityId'] = '';
				this.formData['areaId'] = '';
				this.provinces.length = 0;
				this.cities.length = 0;
				this.areas.length = 0;
			}
			this.selectProvicesByCountryId(newVal);
		},
		'formData.proviceId'(newVal, oldVal) {		//监听省份变化，清空子级数据
			if(oldVal && (newVal != oldVal)) {
				this.formData['cityId'] = '';
				this.formData['areaId'] = '';
				this.cities.length = 0;
				this.areas.length = 0;
			}
			this.selectCityByProvinceId(newVal);
		},
		'formData.cityId'(newVal, oldVal) {		//监听城市变化，清空子级数据
			if(oldVal && (newVal != oldVal)) {
				this.formData['areaId'] = '';
				this.areas.length = 0;
			}
			this.selectAreaByCityId(newVal);
		},
		status(newVal) {
			if(newVal[0] == 3) {
				this.formData['id'] ? this.updateInfo('系统参数修改成功', newVal[0]) : this.addInfo('系统参数新增成功', newVal[0]);
			} else if(newVal[0] == 4) {
				this.addInfo('账套新增成功', newVal[0]);
			} else if(newVal[0] == 6) {
				this.updateInfo('账套修改成功', newVal[0]);
			}
		}
	},
	methods: {
		getSystemInfo() {		//获取系统信息
			this.$http.get(this.$url + 'systemParameters/selectSystemInfo').then(res => {
                if(res.data.code == 20001) {
                    if(res.data.data) {
						//如果是普通系统信息新增，修改操作，就更新系统id
						let status = this.$store.state.accountStore.status;
                        if(status[0] == 3) this.$store.commit('updateSystemId', res.data.data['id']);
                        this.formData = res.data.data;
                        this.isEditRegCode = false;         //有系统信息时，注册码再也不可编辑
                    } else {
                        this.isEditRegCode = true;          //没有系统信息时，注册码可以编辑
                    }
                } else {
                    setTimeout(() => {
                        this.loading = false;
                        this.$message({message: res.data.msg || '获取信息失败', duration: 1500, type: 'error'});
                    }, 3000);
                }
            });
		},
		getSystemInfoByAccountSetId(id) {			//根据账套id获取账套数据
        	this.$http.get(this.$url + 'systemParameters/selectAccountSetById?id=' + id).then(res => {
                if(res.data.code == 20001) {
                    if(res.data.data) {
						this.formData = res.data.data;
                        this.isEditRegCode = false;         //有系统信息时，注册码再也不可编辑
                    } else {
                        this.isEditRegCode = true;          //没有系统信息时，注册码可以编辑
                    }
                }
            })
        },
		getCountries() {			//获取国家数据
			this.$http.get(this.$url + 'city/findCountry').then(res => {
				if(res.data.code == 20001) {
					if(res.data.data && res.data.data.length > 0) {
						this.countries = res.data.data;
					}
				}
			});
		},
		selectProvicesByCountryId(countryId) {			//通过国家id获取省份数据
			this.$http.get(this.$url + 'city/findProvince?parentId=' + countryId).then(res => {
				if(res.data.code == 20001) {
					this.loading = false;
					if(res.data.data && res.data.data.length > 0) {
						this.provinces = res.data.data;
					}
				}
			});
		},
		selectCityByProvinceId(proviceId) {			//通过省份id获取城市数据
			this.$http.get(this.$url + 'city/findCity?parentId=' + proviceId).then(res => {
                if(res.data.code == 20001) {
                	this.loading = false;
                    if(res.data.data && res.data.data.length > 0) {
                        this.cities = res.data.data;
                    }
                }
            });
		},
		selectAreaByCityId(cityId) {			//通过城市id获取区县数据
			this.$http.get(this.$url + 'city/findDistrict?parentId=' + cityId).then(res => {
                if(res.data.code == 20001) {
                	this.loading = false;
                    if(res.data.data && res.data.data.length > 0) {
                        this.areas = res.data.data;
                    }
                }
            });
		},
		selectCurrentName() {
			
		},
		addInfo(msg, status) {			//新增信息
			this.$refs['formRef'].validate((valid) => {
                if (valid) {
                	if(this.formData['id']) delete this.formData['id'];
					let data = {
		                companyNameChinese: this.formData['companyNameChinese'],
		                companyNameEnglish: this.formData['companyNameEnglish'] || '',
		                accountSet: this.formData['accountSet'],
		                registrationCode: this.formData['registrationCode'],
		                companyAbbreviationChinese: this.formData['companyAbbreviationChinese'] || '',
		                companyAbbreviationEnglish: this.formData['companyAbbreviationEnglish'] || '',
		                industry: Number(this.formData['industry']),
		                dutyParagraph: this.formData['dutyParagraph'] || '',
		                bankAccount: this.formData['dutyParagraph'] || '',
		                countryId: this.formData['countryId'] || '',
		                proviceId: this.formData['proviceId'] || '',
		                cityId: this.formData['cityId'] || '',
		                areaId: this.formData['areaId'] || '',
		                addressChinese: this.formData['addressChinese'] || '',
		                addressEnglish: this.formData['addressEnglish'] || '',
		                phone: this.formData['phone'] || '',
		                fax: this.formData['fax'] || '',
		                email: this.formData['email'] || '',
		                currencyCode: this.formData['currencyCode'] || 'RMB',
		                currencyName: this.formData['currencyName'] || '人民币',
		                smallDigit: this.formData['smallDigit'] || 2
					}
					this.$http({
		                url: this.$url + 'systemParameters/insertSystemInformation',
		                method: 'post',
		                params: data
		            }).then(res => {
		                if(res.data.code == 20001) {
		                    this.$message({message: msg, type: 'success', duration: 1500});
		                    setTimeout(() => {
		                        if(status === 3) {
		                            this.$store.commit('updateCompanyNames', data['companyNameChinese']);      //如果是系统信息添加，更新公司名称
		                        }
		                        this.getSystemInfo();       //新增成功后一秒钟获取系统id
		                    }, 1000);
		                } else {
		                    this.$message.error(res.data.msg || '新增信息失败');
		                }
		            });
                }
            });
		},
		updateInfo(msg, status) {			//修改信息
			delete this.formData['createTime'];
            delete this.formData['updateTime'];
            this.$http({
                url: this.$url + 'systemParameters/updateSystemInformation',
                method: 'post',
                params: this.formData
            }).then(res => {
                if(res.data.code == 20001) {
                    this.$message({message: msg, type: 'success', duration: 1500});
                    setTimeout(() => {
                        //如果是账套修改，判断当前修改的账套id是不是和系统id一致，一致的话，更新公司名称
                        if(status === 6) {
                            if(this.formData['id'] == this.systemId) {
                                this.$store.commit('updateCompanyNames', this.formData['companyNameChinese']);      //如果是系统信息添加，更新公司名称
                            }
                        }
                        //如果是普通系统信息修改，更新公司名称
                        if(status == 3) {
                            this.$store.commit('updateCompanyNames', this.formData['companyNameChinese']);      //如果是系统信息添加，更新公司名称
                        }
                        this.getSystemInfo();       //新增成功后一秒钟获取系统id
                    }, 1000);
                } else {
                    this.$message.error(res.data.msg);
                }
            });
		},
		statusOperation() {
			if(this.status[0] == 1) {		//查看账套信息
				this.isEdit = false;
				let accountSetId = this.$store.state.accountStore.accountSetId;
				this.getSystemInfoByAccountSetId(accountSetId);
			} else if(this.status[0] == 2) {		//查看系统信息
				this.getSystemInfo();
				this.isEdit = true;
			} else if(this.status[0] == 4) {		//新增账套
				this.formData = {
					currencyCode: 'RMB',
            		currencyName: '人民币',
            		smallDigit: 2
				};
			} else if(this.status[0] == 5) {		//查看修改账套信息
				let accountSetId = this.$store.state.accountStore.accountSetId;
				this.getSystemInfoByAccountSetId(accountSetId);
			}
		}
	},
	created() {
		if(this.status.length > 0) {
			this.statusOperation();
		}
		this.$nextTick(() => {
			if(this.status[0] != 1 && this.status[0] != 4 && this.status[0] != 5) {
				this.getSystemInfo();
			}
			this.getCountries();
			this.$store.dispatch('accountStore/getIndustry', this.$url + 'industry/selectIndustryCategories');      //获取行业大类数据
		});
	}
}
</script>
<style scoped>
	.form {
		width: 600px;
		margin: 0 auto;
		padding: 20px 0;
		box-sizing: border-box;
	}
	.line {border: 1px solid #409eff;padding: 20px;border-radius: 6px;position: relative;}
    .line .el-form-item:last-child {margin-bottom: 0 !important;}
    .line:before {
        content: '记账本位币';
        position: absolute;
        top: -10px;
        left: 20px;
        background-color: #fff;
        font-size: 14px;
        padding-left: 10px;
        padding-right: 10px;
        color: #409eff;
    }
</style>